#include "index.h"
#include "qmessagebox.h"
#include "ui_index.h"
#include "add.h"
#include "web.h"
#include "opt.h"
#include "http.h"
#include "thread.h"
#include "updatadialog.h"
#include<QCombobox>
#include    <QTcpServer>
#include    <QLabel>
#include    <QtNetwork>
#include <QTcpSocket>
#include <QString>
#include "mainwindow.h"
QStringList cai={"选择菜系","粤系","湘系","苏系","闽系","浙系","徽系","鲁系","川系"};
QStringList fen={"选择店铺","高分店铺","最新店铺","热门店铺"};
index::index(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::index)
{
    ui->setupUi(this);
   // this->setCentralWidget(ui->splitter);
    this->setWindowFlags(Qt::Dialog | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint);


    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);      //不能编辑
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);     //行选择
    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);    //单行选择
    ui->tableView->setAlternatingRowColors(true);
    //下拉框
    ui->comboBox->addItem("点击选择");
    ui->comboBox->addItem("店铺");
    ui->comboBox->addItem("订单");
    ui->comboBox->addItem("管理员");
    ui->comboBox->addItem("客服");
    ui->comboBox->addItem("送货员");
    ui->comboBox->addItem("用户");
    ui->comboBox->addItem("物流");
    ui->comboBox->addItem("菜系");
    int currentIndex = ui->comboBox->currentIndex();
    qDebug() << "当前选中项的索引是:" << currentIndex;

    ui->comboBox_2->addItems(fen);
    connect(ui->comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(change(int)));

    //http b;
    //b.start();

    m_s = new MyTcpServer(this);

    connect(m_s,&MyTcpServer::newDescriptor,this,[=](qintptr sock)
            {
       // QTcpSocket* tcp = m_s->nextPendingConnection();
        Sthread* sub = new Sthread(sock);
        sub->start();
        connect(sub,&Sthread::over,this,[=]()
                {
            sub->exit();
            sub->wait();
            sub->deleteLater();
            m_s->listen(QHostAddress::LocalHost, 8080);
            qDebug() << "Web服务开启8080";
        });
    });
}

index::~index()
{
    delete ui;
}

void index::selectData()
{
    //1. 创建数据模型，查询数据
    qryModel=new QSqlQueryModel(this);
    //connect( ui->comboBox,SIGNAL(currentIndexChange(int)),this,SLOT(datatablechange(int)));
    qDebug() << "tablename"<<tablename;
    QString data = "SELECT * FROM ";
    QString str;
    QString table = data + tablename + str +caixixuanze+";";
    qDebug() << "tablename"<<table;
    qryModel->setQuery(table);
    if (qryModel->lastError().isValid())
    {
        //QMessageBox::critical(this, "错误", "数据表查询错误,错误信息\n"
        //                                        +qryModel->lastError().text());
       // return;
    }
  //  ui->statusBar->showMessage(QString("记录条数：%1").arg(qryModel->rowCount()));//显示记录条数

    //2. 设置字段显示标题
    // QSqlRecord rec=qryModel->record();  //获取一个空记录，为了获取字段序号
    // qryModel->setHeaderData(rec.indexOf("empNo"),  Qt::Horizontal, "工号");
    // qryModel->setHeaderData(rec.indexOf("Name"),   Qt::Horizontal, "姓名");
    // qryModel->setHeaderData(rec.indexOf("Gender"), Qt::Horizontal, "性别");
    // qryModel->setHeaderData(rec.indexOf("Birthday"),   Qt::Horizontal, "出生日期");
    // qryModel->setHeaderData(rec.indexOf("Province"),   Qt::Horizontal, "省份");
    // qryModel->setHeaderData(rec.indexOf("Department"), Qt::Horizontal, "部门");
    // qryModel->setHeaderData(rec.indexOf("Salary"),     Qt::Horizontal, "工资");

    //3. 创建选择模型
    selModel=new QItemSelectionModel(qryModel,this);
    // connect(selModel,&QItemSelectionModel::currentRowChanged,
    //         this, &index::do_currentRowChanged);
    ui->tableView->setModel(qryModel);
    ui->tableView->setSelectionModel(selModel);
    //    ui->tableView->resizeColumnsToContents();
    //    ui->tableView->horizontalHeader()->setStretchLastSection(true);

    //4. 创建数据映射
    dataMapper= new QDataWidgetMapper(this);
    dataMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
    dataMapper->setModel(qryModel);

    // //界面组件与数据模型的具体字段之间的映射
    // dataMapper->addMapping(ui->dbSpinEmpNo, rec.indexOf("empNo"));
    // dataMapper->addMapping(ui->dbEditName,  rec.indexOf("Name"));
    // dataMapper->addMapping(ui->dbComboSex,  rec.indexOf("Gender"));
    // dataMapper->addMapping(ui->dbEditBirth, rec.indexOf("Birthday"));
    // dataMapper->addMapping(ui->dbComboProvince, rec.indexOf("Province"));
    // dataMapper->addMapping(ui->dbComboDep,      rec.indexOf("Department"));
    // dataMapper->addMapping(ui->dbSpinSalary,    rec.indexOf("Salary"));

    dataMapper->toFirst();  //移动到首记录
    // ui->actOpenDB->setEnabled(false);
}

void openbase()
{
    QSqlQuery query("SELECT * FROM dbo.dianpu;");
    qDebug()<<"ID     LoginName        LoginTime                LogoutTime        OPeration";
    while (query.next())
    {
        int ID = query.value(0).toInt();
        QString LoginName = query.value(1).toString();
        QString LoginTime = query.value(2).toString();
        QString LogoutTime = query.value(3).toString();
        int OPeration = query.value(4).toInt();

        qDebug()<<QString("%1       %2       %3         %4      %5")
                        .arg(ID).arg(LoginName).arg(LoginTime).arg(LogoutTime).arg(OPeration);
    }


    //数据库关闭
    // db.close();
}

void index::updateRecord(int recNo)
{
    //------------------------------------------------------------------获取第一个字段名
    int currentIndex = ui->comboBox->currentIndex();
    qDebug() << "当前选中项的索引是:" << currentIndex;
    datatablechange(currentIndex);
    changename(currentIndex);//查列名
    qDebug() << "column:" << column;
    qDebug()<<"更新第几条："<<recNo;
    QSqlRecord  curRec=qryModel->record(recNo); //获取数据模型的一条记录
    qDebug()<<"更新："<<curRec;
    QString empNo=curRec.value(column).toString();    //获取字段内容（中文）
    //--------------------------------------------------------------------------拼接SQL语句
    qDebug()<<"更新name："<<empNo;
    QSqlQuery query;
    //query.prepare("select * from employee where EmpNo = :ID");dbo.dianpu

    QString str1 = " where "+column+" = '";//北方饺子馆'";
    QString table = "select * from "+tablename+str1+empNo+"'";
    qDebug()<<"SQL："<<table;
    //---------------------------------------------------------------------------执行SQL语句
    query.prepare(table);
    //query.addBindValue(empNo);
    //query.bindValue(":ID",empNo);
    query.exec();
    query.first();
    if (!query.isValid())   //无有效记录
        return;

    curRec=query.record();  //获取当前记录

    //sd->show();
    //updatadialog    *dataDialog=new updatadialog(this); //创建对话框
   // Qt::WindowFlags    flags=dataDialog->windowFlags();
    //dataDialog->setWindowFlags(flags | Qt::MSWindowsFixedSizeDialogHint);
    //dataDialog->setUpdateRecord(curRec);
    updatadialog * sd = new updatadialog(this);
    Qt::WindowFlags    flags=sd->windowFlags();
    sd->setWindowFlags(flags | Qt::MSWindowsFixedSizeDialogHint);
    sd->setUpdateRecord(curRec);
    int ret=sd->exec();
    if (ret==QDialog::Accepted)//---------------------------另一个页面点击确定后回来
    {
        QSqlRecord  recData=sd->getRecordData();    //获得对话框返回的记录

        //query.addBindValue(recData.value("shopname").toString());
        // query.bindValue(":sale",  recData.value("sale"));
        // query.bindValue(":name",recData.value("name"));
        // query.bindValue(":ID",recData.value("ID"));
        // query.bindValue(":phone",  recData.value("phone"));
        // query.bindValue(":addre",  recData.value("addre"));
        // query.bindValue(":time",    recData.value("time"));
        // query.bindValue(":Password",   recData.value("Password"));
        // query.bindValue(":way",   recData.value("way"));
        // query.bindValue(":monoy",   recData.value("monoy"));
        // query.bindValue(":orderid",   recData.value("orderid"));

        int currentIndex = ui->comboBox->currentIndex();
        qDebug() << "!!当前选中项的索引是:" << currentIndex;
        switch(currentIndex)
        {
        case 1: //tablename = "dbo.dianpu";
            query.prepare("update dbo.dianpu set sale=?,time=?,mark=? where Shopname =?");
            query.addBindValue(recData.value("sale").toString());
            query.addBindValue(recData.value("time").toString());
            query.addBindValue(recData.value("mark").toString());
            query.addBindValue(recData.value("Shopname").toString());
            break;
        case 2: //tablename = "dbo.dingdan";
            query.prepare("update dbo.dingdan set phone=?,orderid=?,money=?,way=?,name=?,addre=? where ID=?");
            query.addBindValue(recData.value("phone").toString());
            query.addBindValue(recData.value("orderid").toString());
            query.addBindValue(recData.value("money").toString());
            query.addBindValue(recData.value("way").toString());
            query.addBindValue(recData.value("name").toString());
            query.addBindValue(recData.value("addre").toString());
            query.addBindValue(recData.value("ID").toString());

            break;
        case 3: //tablename = "dbo.guanliyuan";
            query.prepare("update dbo.guanliyuan set Password=? where ID=?");
            query.addBindValue(recData.value("Password").toString());
            query.addBindValue(recData.value("ID").toString());
            break;
        case 4: //tablename = "dbo.kefu";

            query.prepare("update dbo.kefu set Name=? , Shopname=? where ID=?");
            query.addBindValue(recData.value("name").toString());
            query.addBindValue(recData.value("shopname").toString());
            query.addBindValue(recData.value("ID").toString());
            break;
        case 5: //tablename = "dbo.sonhuoyuan";
            query.prepare("update dbo.sonhuoyuan set name=?,phone=?,shopname=? where ID=?");
            query.addBindValue(recData.value("name").toString());
            query.addBindValue(recData.value("phone").toString());
            query.addBindValue(recData.value("shopname").toString());
            query.addBindValue(recData.value("ID").toString());
            break;
        case 6: //tablename = "dbo.user1";
            query.prepare("update dbo.user1 set name=?,phone=?,Password=? where ID=?");
            query.addBindValue(recData.value("name").toString());
            query.addBindValue(recData.value("phone").toString());
            query.addBindValue(recData.value("Password").toString());
            query.addBindValue(recData.value("ID").toString());
            break;
        case 7: //tablename = "dbo.wuliu";
            query.prepare("update dbo.wuliu set phone=?,time=? where ID=?");
            query.addBindValue(recData.value("phone").toString());
            query.addBindValue(recData.value("time").toString());
            query.addBindValue(recData.value("ID").toString());
            break;
        case 8: //tablename = "dbo.caidan";
            query.prepare("update dbo.caidan set cuisine=? ,name=?  where ID=?");
            query.addBindValue(recData.value("cuisine").toString());
            query.addBindValue(recData.value("name").toString());
            query.addBindValue(recData.value("ID").toString());
            break;
        }

        if (!query.exec())
            QMessageBox::critical(this, "错误", "记录更新错误\n"+query.lastError().text());
        else
        {
            // Qt 6.5.1中修改
            QString str= qryModel->query().executedQuery();   //获取执行过的SQL语句
            qryModel->setQuery(str);     //重新执行SQL语句
            //            qryModel->query().exec();   //数据模型重新查询数据，更新tableView显示
        }
    }

    delete sd;      //删除对话框
}

void index::on_pushButton_clicked(bool checked)
{
    int currentIndex = ui->comboBox->currentIndex();
    qDebug() << "当前选中项的索引是:" << currentIndex;
    datatablechange(currentIndex);
    selectData();
}

void index::changename(int index)
{
    switch(index)
    {
    case 1: column = "shopname";
        break;
    case 2: column = "phone";
        break;
    case 3: column = "ID";
        break;
    case 4: column = "ID";
        break;
    case 5: column = "ID";
        break;
    case 6: column = "ID";
        break;
    case 7: column = "phone";
        break;
    case 8: column = "ID";
        break;
    }
}

void index::on_pushButton_2_clicked(bool checked)
{
    //add * ds =new add;
    //ds->show();
    int currentIndex = ui->comboBox->currentIndex();
    ad(currentIndex);
    // opt * ds =new opt;
    // ds->show();

}

void index::ad(int recNo)
{
    int currentIndex = ui->comboBox->currentIndex();
    QSqlQuery query;

    add * ss = new add(this);
    Qt::WindowFlags    flags=ss->windowFlags();
    ss->setWindowFlags(flags | Qt::MSWindowsFixedSizeDialogHint);
    ss->opreation(currentIndex);
    int ret=ss->exec();
    if (ret==QDialog::Accepted)//---------------------------另一个页面点击确定后回来
    {
 //        QSqlRecord  recData=ss->getBack();    //获得对话框返回的记录
 //        qDebug()<<"recData:  "<<recData;
 //        //query.addBindValue(recData.value("shopname").toString());
 //        // query.bindValue(":sale",  recData.value("sale"));
 //        // query.bindValue(":name",recData.value("name"));
 //        // query.bindValue(":ID",recData.value("ID"));
 //        // query.bindValue(":phone",  recData.value("phone"));
 //        // query.bindValue(":addre",  recData.value("addre"));
 //        // query.bindValue(":time",    recData.value("time"));
 //        // query.bindValue(":Password",   recData.value("Password"));
 //        // query.bindValue(":way",   recData.value("way"));
 //        // query.bindValue(":monoy",   recData.value("monoy"));
 //        // query.bindValue(":orderid",   recData.value("orderid"));

 //        int currentIndex = ui->comboBox->currentIndex();
 //        qDebug() << "!!当前选中项的索引是:" << currentIndex;
 //        switch(currentIndex)
 //        {
 //        case 0: //tablename = "dbo.dianpu";
 //            query.prepare("insert into dbo.dianpu (sale,shopname) values (?,'?')");
 //            query.addBindValue(recData.value("sale").toString());
 //            query.addBindValue(recData.value("shopname").toString());
 //            qDebug()<<"sale:"<<recData.value("sale");
 //            qDebug()<<"shopname:"<<recData.value("shopname").toString();
 //            break;
 //        case 1: //tablename = "dbo.dingdan";
 //            query.prepare("insert into dbo.dingdan (phone,orderid,money,way,name,addre,ID) values (?,?,?,?,?,?,?)");
 //            //query.prepare("update dbo.dingdan set phone=?,orderid=?,money=?,way=?,name=?,addre=? where ID=?");
 //            query.addBindValue(recData.value("phone").toString());
 //            query.addBindValue(recData.value("orderid").toString());
 //            query.addBindValue(recData.value("money").toString());
 //            query.addBindValue(recData.value("way").toString());
 //            query.addBindValue(recData.value("name").toString());
 //            query.addBindValue(recData.value("addre").toString());
 //            query.addBindValue(recData.value("ID").toString());

 //            break;
 //        case 2: //tablename = "dbo.guanliyuan";
 //            query.prepare("insert into dbo.guanliyuan (Password,ID) values(?,?)");
 //            //query.prepare("update dbo.guanliyuan set Password=? where ID=?");
 //            query.addBindValue(recData.value("Password").toString());
 //            query.addBindValue(recData.value("ID").toString());
 //            break;
 //        case 3: //tablename = "dbo.kefu";
 //            query.prepare("insert into dbo.kefu (name,shopname,ID) values(?,?,?)");
 //            //query.prepare("update dbo.kefu set Name=? , Shopname=? where ID=?");
 //            query.addBindValue(recData.value("name").toString());
 //            query.addBindValue(recData.value("shopname").toString());
 //            query.addBindValue(recData.value("ID").toString());
 //            break;
 //        case 4: //tablename = "dbo.sonhuoyuan";
 //            query.prepare("insert into dbo.kefu (name,phone,shopname,ID) values (?,?,?,?)");
 //            //query.prepare("update dbo.sonhuoyuan set name=?,phone=?,shopname=? where ID=?");
 //            query.addBindValue(recData.value("name").toString());
 //            query.addBindValue(recData.value("phone").toString());
 //            query.addBindValue(recData.value("shopname").toString());
 //            query.addBindValue(recData.value("ID").toString());
 //            break;
 //        case 5: //tablename = "dbo.user1";
 //            query.prepare("insert into dbo.kefu (name,phone,Password,ID) values (?,?,?,?)");
 //            //query.prepare("update dbo.user1 set name=?,phone=?,Password=? where ID=?");
 //            query.addBindValue(recData.value("name").toString());
 //            query.addBindValue(recData.value("phone").toString());
 //            query.addBindValue(recData.value("Password").toString());
 //            query.addBindValue(recData.value("ID").toString());
 //            break;
 //        case 6: //tablename = "dbo.wuliu";
 //            query.prepare("insert into dbo.kefu (phone,time,ID) values (?,'?',?)");
 // //           //query.prepare("update dbo.wuliu set phone=?,time='?' where ID=?");
 //            query.addBindValue(recData.value("phone").toString());
 //            query.addBindValue(recData.value("time").toString());
 //            query.addBindValue(recData.value("ID").toString());
 //            break;
 //        case 7: //tablename = "dbo.wuliu";
 //            query.prepare("insert into dbo.kefu (cuisine,name,ID) values (?,?,?,?)");
 //            //query.prepare("update dbo.caidan set cuisine=? ,name=?  where ID=?");
 //            query.addBindValue(recData.value("cuisine").toString());
 //            query.addBindValue(recData.value("name").toString());
 //            query.addBindValue(recData.value("ID").toString());
 //            break;
 //        }

 //        if (!query.exec())
 //            QMessageBox::critical(this, "错误", "记录更新错误\n"+query.lastError().text());
 //        else
 //        {
 //            // Qt 6.5.1中修改
 //            QString str= qryModel->query().executedQuery();   //获取执行过的SQL语句
 //            qryModel->setQuery(str);     //重新执行SQL语句
 //            //            qryModel->query().exec();   //数据模型重新查询数据，更新tableView显示
 //        }
    }
    selectData();
}

void index::on_pushButton_3_clicked(bool checked)

{
    //http * ds =new http; //跳转页面
   // ds->show();
    //------------------------------------------
   // web as;
   // as.start();
    //selectData();
    m_s->listen(QHostAddress::LocalHost, 8080);
    qDebug() << "Web服务开启8080";
}

void index::on_pushButton_4_clicked(bool checked)
{
    m_s->close();
    qDebug() << "Web服务关闭";
}


void index::on_tableView_clicked(const QModelIndex &index)
{
    //int curRecNo=selModel->currentIndex().row();
    int curRecNo=index.row();
    value = curRecNo;
   // updateRecord(curRecNo);
}



void index::on_tableView_activated(const QModelIndex &index)
{

}


void index::on_tableView_doubleClicked(const QModelIndex &index)
{
    int curRecNo=index.row();
    qDebug()<<"第几行："<<curRecNo;
    updateRecord(curRecNo);
}

void index::datatablechange(int index)
{
  //  QString tablename;
    switch(index)
    {
    case 1: tablename = "dbo.dianpu";
        break;
    case 2: tablename = "dbo.dingdan";
        break;
    case 3: tablename = "dbo.guanliyuan";
        break;
    case 4: tablename = "dbo.kefu";
        break;
    case 5: tablename = "dbo.sonhuoyuan";
        break;
    case 6: tablename = "dbo.user1";
        break;
    case 7: tablename = "dbo.wuliu";
        break;
    case 8: tablename = "dbo.caidan";
        break;
    }
    //return tablename;
}

void index::change(int index)
{
    ui->comboBox_2->clear();
    switch(index)
    {
    case 1: ui->comboBox_2->addItems(fen);
        connect(ui->comboBox_2,SIGNAL(currentIndexChanged(int)),this,SLOT(changedd(int)));
        break;

    case 8: ui->comboBox_2->addItems(cai);
        connect(ui->comboBox_2,SIGNAL(currentIndexChanged(int)),this,SLOT(changed(int)));

        break;
    }
}
void index::changed(int index){

    switch(index){
    case 1: caixixuanze = " where cuisine = '粤菜'";
        break;
    case 2: caixixuanze = " where cuisine = '湘菜'";
        break;
    case 3: caixixuanze = " where cuisine = '苏菜'";
        break;
    case 4: caixixuanze = " where cuisine = '闽菜'";
        break;
    case 5: caixixuanze = " where cuisine = '浙菜'";
        break;
    case 6: caixixuanze = " where cuisine = '徽菜'";
        break;
    case 7: caixixuanze = " where cuisine = '鲁菜'";
        break;
    case 8: caixixuanze = " where cuisine = '川菜'";
        break;
    default: caixixuanze = " ";
    }

}

void index::changedd(int index)//店铺分数
{
    switch(index){
    case 0: caixixuanze = " ";
        break;
    case 1: caixixuanze = " where  mark>=4";
        break;
    case 2: caixixuanze = " WHERE (time IN (SELECT MIN(time)FROM dbo.dianpu ))";
        break;
    case 3: caixixuanze = " WHERE sale > (SELECT AVG(sale) FROM dbo.dianpu)";
        break;
    }

}

void index::on_pushButton_5_clicked(bool checked)//删除
{
    int  recNo1 = value;
    int currentIndex = ui->comboBox->currentIndex();
    qDebug() << "删除当前选中项的索引是:" << currentIndex;
    datatablechange(currentIndex);
    changename(currentIndex);//查列名
    qDebug() << "column:" << column;
    qDebug()<<"删除第几条："<<recNo1;
    QSqlRecord  curRec=qryModel->record(recNo1); //获取数据模型的一条记录
    qDebug()<<"删除："<<curRec;
    QString empNo=curRec.value(column).toString();    //获取字段内容（中文）
    //--------------------------------------------------------------------------拼接SQL语句
    qDebug()<<"删除name："<<empNo;
    QSqlQuery query;
    //query.prepare("select * from employee where EmpNo = :ID");dbo.dianpu

    QString str1 = " where "+column+" = '";//北方饺子馆'";
    QString table = "delete  from "+tablename+str1+empNo+"'";
    qDebug()<<"SQL："<<table;
    //---------------------------------------------------------------------------执行SQL语句
    query.prepare(table);
    //query.addBindValue(empNo);
    //query.bindValue(":ID",empNo);
    //query.exec();
    if (!query.exec())
        QMessageBox::critical(this, "错误", "记录更新错误\n"+query.lastError().text());
    selectData();
}




void index::on_pushButton_6_clicked(bool checked)
{
    MainWindow *ds = new MainWindow;
    ds->show();
    this->close();
}

